package com.corn.juc.fork;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2022/5/9 14:39
 */

public class ForkJoinPoolDemo {

    static class SumForkJoinTask extends RecursiveTask<Integer> {

        private int start;

        private int end;

        SumForkJoinTask(int start, int end) {
            this.start = start;
            this.end = end;
        }


        @Override
        protected Integer compute() {
            if (end - start < 2000) {
                System.out.println(Thread.currentThread().getName() + " 开始执行: " + start + "-" + end);
                int sum = 0;
                for (int i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            }
            SumForkJoinTask left = new SumForkJoinTask(start, (start + end) / 2);
            SumForkJoinTask right = new SumForkJoinTask((start + end) / 2 + 1, end);
            right.fork();
            return left.compute() + right.join();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 采用Fork/Join来异步计算1+2+3+…+10000的结果
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        ForkJoinTask<Integer> forkJoinTask = new SumForkJoinTask(1, 10000);
        forkJoinPool.submit(forkJoinTask);
        System.out.println(forkJoinTask.get());
    }
}
